package com.guapi.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.guapi.annotation.SelfController;
import com.guapi.dao.*;
import com.guapi.exception.SelfException;
import com.guapi.service.AuthService;
import com.guapi.service.MenuService;
import com.guapi.service.RoleService;
import com.guapi.util.request.SelfRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@SelfController
@RequestMapping("/role")
@ResponseBody
public class RoleController extends BaseController<Role> {

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthService authService;

    @Autowired
    private MenuService menuService;

    @RequestMapping("/list")
    public ResponseData getRoleList(HttpServletRequest request, @RequestBody Map data) {
        responseData = new ResponseData();
        List<Role> roleList;
        String roleName = "";
        String roleDesc = "";
        Map searchStr = (Map) data.get("searchStr");
        if (searchStr != null) {
            roleName = (String) searchStr.get("name");
            roleDesc = (String) searchStr.get("desc");

        }
        startPage(data);

        if (StrUtil.isAllEmpty(roleName, roleDesc)) {
            roleList = roleService.list();
        } else {
            Role role = new Role();
            if (StrUtil.isNotEmpty(roleName)) {
                role.setRoleName(roleName);
            }
            if (StrUtil.isNotEmpty(roleDesc)) {
                role.setRoleDesc(roleDesc);
            }
            roleList = roleService.getByFuzzy(role);
        }
        responseData.setRows(roleList);
        responseData.setSuccess(true);
        return responseData;
    }

    @RequestMapping("/save")
    public ResponseData addUser(HttpServletRequest request, @RequestBody Role role) {
        SelfRequest selfRequest = createRequest(request);

        responseData = new ResponseData();
        User loginUser = getLoginUser();
        if (role.getCreateDate() == null) {
            role.setCreateBy(String.valueOf(loginUser.getId()));
        } else {
            role.setUpdateBy(String.valueOf(loginUser.getId()));
        }
        if (roleService.saveOrUpdate(role)) {
            responseData.setData("role", role);
            responseData.setSuccess(true);
        } else {
            throw new SelfException("500", "添加角色失败，请稍后重试");
        }
        return responseData;
    }

    @RequestMapping("/delete")
    public ResponseData deleteRole(HttpServletRequest request, @RequestBody Role role) {
        SelfRequest selfRequest = createRequest(request);
        responseData = new ResponseData();
        User loginUser = getLoginUser();
        role.setUpdateBy(String.valueOf(loginUser.getId()));
        if (roleService.deleteEntity(role).equals(role)) {
            responseData.setSuccess(true);
            responseData.setData("role", role);
        }
        return responseData;
    }

    @RequestMapping("/auth/show")
    public ResponseData showAuth(HttpServletRequest request, @RequestBody Role role) {
        responseData = new ResponseData();
        List<Integer> menuList = new ArrayList<>();
        List<Auth> authList = authService.getByConditions(new Auth().setRoleId(role.getId()));
        if (CollectionUtil.isNotEmpty(authList)) {
            authList.forEach(auth -> menuList.add(auth.getMenuId()));
            List<Menu> menus = menuService.listByIds(menuList);
            responseData.setRows(menus);
        }
        responseData.setSuccess(true);
        return responseData;
    }

    @RequestMapping("/auth/change")
    public ResponseData changeAuth(HttpServletRequest request, @RequestBody Map map) {
        responseData = new ResponseData();
        User loginUser = getLoginUser();
        String loginRoleId = loginUser.getRole();
        Role loginRole = roleService.getById(loginRoleId);
        if (Integer.parseInt(loginRole.getRoleAuth()) > 10) {
            throw new SelfException("您的权限不足，无法修改该数据！");
        }
        Role role = BeanUtil.toBean(map.get("role"), Role.class);
        Integer roleId = role.getId();
        List<Integer> menuIds = (List) map.get("menuIds");

        if (CollectionUtil.isEmpty(menuIds)) {
            //删除角色对应的所有菜单
            authService.deleteEntity(new Auth().setRoleId(roleId));
        } else {
            List<Auth> databaseAuth = authService.getByConditions(new Auth().setRoleId(roleId));
            List<Auth> authList = new ArrayList<>();

            if (CollectionUtil.isEmpty(databaseAuth)) {
                //数据库没有相关权限配置，可以全部加入
                menuIds.forEach(id -> {
                    authService.save(new Auth().setRoleId(roleId).setMenuId(id));
                });
            } else {
                List<Auth> deleteAuths = databaseAuth.stream().filter(auth -> {
                    if (!menuIds.contains(auth.getMenuId())) {
                        authService.deleteEntity(auth);
                        return true;
                    } else {
                        menuIds.remove(auth.getMenuId());
                        return false;
                    }
                }).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(menuIds)) {
                    menuIds.forEach(id -> {
                        authService.save(new Auth().setRoleId(roleId).setMenuId(id));
                    });
                }
                System.out.println();


            }
        }

        responseData.setSuccess(true);
        return responseData;
    }
}
